const path = require("path");
const os = require("os");
const webpack = require("webpack");
const WebpackBar = require("webpackbar");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const ManifestPlugin = require("webpack-manifest-plugin");
const HappyPack = require("happypack");
const ErrorOverlayPlugin = require("error-overlay-webpack-plugin");

const BUILD_PATH = path.join(__dirname, "../dist");

module.exports = () => {
  const dev = process.env.NODE_ENV !== "production";
  const definePlugin = new webpack.DefinePlugin({
    __isDEV__: dev,
  });

  const webpackConfig = {
    mode: !dev ? "production" : "development",
    stats: { children: false },
    devtool: dev ? "source-map" : false,
    externals: {
      react: "React",
      "react-dom": "ReactDOM",
    },
    plugins: [
      definePlugin,
      new WebpackBar(),
      new HappyPack({
        id: "happy-awesome",
        loaders: ["babel-loader?cacheDirectory=true"],
        threadPool: HappyPack.ThreadPool({
          size: Math.max(1, os.cpus().length - 1),
        }),
      }),

      dev ? new ErrorOverlayPlugin() : null,
      new MiniCssExtractPlugin({
        filename: "[name].css",
      }),
      new ManifestPlugin({
        fileName: "manifest.json",
      }),
    ].filter(Boolean),
    module: {
      rules: [
        {
          test: /\.(jsx?|tsx?)$/,
          loader: "babel-loader",
          include: [
            path.resolve(__dirname, "../src"),
            path.resolve(__dirname, "../server"),
          ],
          options: {
            configFile: path.resolve(__dirname, "./babel.config.js"),
          },
        },
        {
          test: /\.route\.(j|t)s(x?)$/,
          loader: "string-replace-loader",
          options: {
            search: "lazyImport((.*)),",
            replace: (match, p1, offset, string) =>
              dev ? `require${p1}.default,` : `React.lazy(() => import${p1}),`,
            flags: "g",
          },
        },
        {
          test: /\.(css|less)$/i,
          exclude: /(node_module)/,
          use: [
            {
              loader: MiniCssExtractPlugin.loader,
              options: {
                hmr: dev,
              },
            },
            {
              loader: "css-loader",
              options: {
                sourceMap: dev,
                importLoaders: 2,
                modules: false,
              },
            },
            {
              loader: "postcss-loader",
              options: {
                plugins: [
                  require("autoprefixer")(),
                  /* require("postcss-plugin-px2rem")({
                    rootValue,
                    minPixelValue: 1,
                    exclude: /(node_module)/,
                  }), */
                ],
              },
            },
            {
              loader: "less-loader",
              options: {
                javascriptEnabled: true,
              },
            },
          ],
        },
        {
          test: /\.(css|less)$/i,
          include: [path.resolve(__dirname, "../node_modules")],
          use: [
            MiniCssExtractPlugin.loader,
            {
              loader: "css-loader",
            },
            {
              loader: "less-loader",
              options: {
                javascriptEnabled: true,
                // modifyVars: require('../src/theme'),
              },
            },
          ],
        },
        {
          test: /\.(png|jpg|jpeg|gif)$/,
          use: [
            {
              loader: "url-loader",
              options: {
                limit: 1024 * 8,
                name: "./assets/[name].[ext]",
              },
            },
          ],
        },
        {
          test: /\.(woff|woff2|svg|eot|ttf)$/,
          use: [
            {
              loader: "url-loader",
              options: {
                limit: 10240,
                name: "./assets/fonts/[name].[ext]",
              },
            },
          ],
        },
      ],
    },
    resolve: {
      extensions: [".js", ".jsx", ".ts", ".tsx"],
      modules: [
        path.resolve(__dirname, "../src"),
        path.resolve(__dirname, "../node_modules"),
      ],
      alias: {
        "@app": path.resolve(__dirname, "../src"),
      },
    },
  };

  return webpackConfig;
};
